<?php

class Utility_FileFunctions {

    static public function deleteIfExists($str_file)
    {
        if (file_exists($str_file)) {
            unlink($str_file);
        }
    }

    static public function rrmdir($dir) {

        if (is_dir($dir)) {
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (filetype($dir.DIRECTORY_SEPARATOR.$object) == "dir") {
                        self::rrmdir($dir.DIRECTORY_SEPARATOR.$object);
                    } else {
                        unlink($dir.DIRECTORY_SEPARATOR.$object);
                    }
                }
            }
            
            rmdir($dir);
        }

    }

    static public function removeDirectoriesMatching($dir, $str_pattern) {

        if (is_dir($dir)) {
            
            $objects = scandir($dir);
            foreach ($objects as $object) {

                if (
                    ($object != ".") &&
                    ($object != "..")
                ) {

                    $str_file = $dir . DIRECTORY_SEPARATOR . $object;

                    if($str_pattern == $object) {
                        
                        if (filetype($str_file) == "dir") {
                            self::rrmdir($str_file);
                        } else {
                            unlink($str_file);
                        }

                    } else if (filetype($str_file) == "dir") {
                        self::removeDirectoriesMatching($str_file, $str_pattern);
                    }
                    
                }
                
            }

        }

    }

}